package com.ruoyi.im.config;

import com.ruoyi.framework.web.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.tio.server.ServerTioConfig;
import org.tio.websocket.server.WsServerStarter;

import java.io.IOException;


@Component
public class ImStart implements ApplicationRunner {
    @Autowired
    private WsServerStarter wsServerStarter;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ImWsMsgHandler imWsMsgHandler;
    
    @Bean
    private ImWsMsgHandler getImWsMsgHandler() {
        return new ImWsMsgHandler(tokenService);
    }

    @Bean
    private WsServerStarter getWsServerStarter() throws IOException {
        return new WsServerStarter(ImServerConfig.SERVER_PORT, imWsMsgHandler);
    }


    @Override
    public void run(ApplicationArguments args) throws Exception {
        wsServerStarter = new WsServerStarter(ImServerConfig.SERVER_PORT, imWsMsgHandler);
        ServerTioConfig serverTioConfig = wsServerStarter.getServerTioConfig();
        serverTioConfig.setName(ImServerConfig.PROTOCOL_NAME);
        serverTioConfig.setServerAioListener(ImServerAioListener.me);
        //设置ip监控
        serverTioConfig.setIpStatListener(ImIpStatListener.me);
        //设置ip统计时间段
        serverTioConfig.ipStats.addDurations(ImServerConfig.IpStatDuration.IPSTAT_DURATIONS);
        //设置心跳超时时间
        serverTioConfig.setHeartbeatTimeout(ImServerConfig.HEARTBEAT_TIMEOUT);
//        if (P.getInt("ws.use.ssl", 1) == 1) {
//            //如果你希望通过wss来访问，就加上下面的代码吧，不过首先你得有SSL证书（证书必须和域名相匹配，否则可能访问不了ssl）
////            String keyStoreFile = "classpath:config/ssl/keystore.jks";
////            String trustStoreFile = "classpath:config/ssl/keystore.jks";
////            String keyStorePwd = "214323428310224";
//            String keyStoreFile = P.get("ssl.keystore", null);
//            String trustStoreFile = P.get("ssl.truststore", null);
//            String keyStorePwd = P.get("ssl.pwd", null);
//            serverTioConfig.useSsl(keyStoreFile, trustStoreFile, keyStorePwd);
//        }
        wsServerStarter.start();
    }
}
